#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Omar Vega Ramos
# E-mail: ovruni@riseup.net
# License: GNU GPL - GNU General Public License v3.0 or later
# http://www.gnu.org/licenses/gpl.html

import argparse, csv, sys
import os.path

def csv_file(filename):
    if not filename.endswith('.csv'):
        raise argparse.ArgumentTypeError('must be of type *.csv')
    return filename

parser = argparse.ArgumentParser(description='Generate the OSM file with educational centers from a CSV file.')
parser.add_argument('input', type=csv_file, help='name of the input file')
parser.add_argument('-o', '--output', default='schools.osm', help='name of the output file')
args = parser.parse_args()

fw = open(args.output, 'w')
fw.write("<?xml version='1.0' encoding='UTF-8'?>\n")
fw.write("<osm version='0.6' upload='true' generator='JOSM'>\n")
id = -1

#row = [Ubigeo,Departamento,Provincia,Distrito,Cod. CCPP,Nom. CCPP,Localidad,Cod. Local,Cod. Modular,Nom. IIEE,Nivel,Dirección,Docentes,Alumnos,¿ECE?,Grado,Altitud,Fuente,Latitud,Longitud]

with open(args.input, 'r') as fr:
    reader = csv.reader(fr)
    next(reader)
    for row in reader:
        cod_local = row[7]
        cod_modular = row[8]
        name = row[9].title()
        name = name[:1] + name[1:].replace("De ", "de ").replace("La ", "la ").replace("El ", "el ").replace("Las ", "las ").replace("Los ", "los ").replace("Del ", "del ").replace(" Y ", " y ")
        name = name.replace("'", "&apos;").replace("&", "&amp;")
        level = row[10]
        address = row[11].title().replace("'", "&apos;")
        latitude = row[18]
        longitude = row[19]

        if level.find('CETPRO') != -1 or level.find('Superior') != -1 or level.find('Escuelas') != -1 or level.find('Magisterial') != -1 :
            tag = 'college'
            if level.find('CETPRO') != -1 :
                name = 'CETPRO ' + name
            if level.find('Superior') != -1 :
                name = 'IST ' + name
            if level.find('Escuela') != -1 :
                name = 'Escuela ' + name
            if level.find('Magisterial') != -1 :
                name = 'ISP ' + name

        if level.find('Inicial') != -1 or level.find('PRONOEI') != -1 :
            tag = 'kindergarten'
            if level.find('Cuna') != -1 :
                name = 'Inicial Cuna - Jardín ' + name
            else :
                name = 'Inicial Jardín ' + name
            if level.find('PRONOEI') != -1 :
                name = 'PRONOEI ' + name

        if level.find('Primaria') != -1 or level.find('Secundaria') != -1 or level.find('Alternativa') != -1 or level.find('Especial') != -1 :
            tag = 'school'
            if level.find('Primaria') != -1 or level.find('Secundaria') != -1  :
                name = 'Colegio ' + name
            if level.find('Alternativa') != -1 :
                name = 'CEBA ' + name
            if level.find('Especial') != -1 :
                name = 'Centro de educación especial ' + name

        fw.write("  <node id='" + str(id) + "' action='modify' visible='true' lat='" + latitude + "' lon='" + longitude + "'>\n")
        fw.write(" <tag k='amenity' v='" + tag + "' />\n")
        fw.write(" <tag k='name' v='" + name + "' />\n")
        fw.write(" <tag k='addr:street' v='" + address + "' />\n")
        if cod_local != "" :
            fw.write(" <tag k='pe:minedu:codigo_local' v='" + cod_local + "' />\n")
        fw.write(" <tag k='pe:minedu:codigo_modular' v='" + cod_modular + "' />\n")
        fw.write(" <tag k='source' v='www.minedu.gob.pe' />\n")
        fw.write("  </node>\n")
        id = id - 1

fw.write("</osm>")
fw.close()
sys.exit("Generated '" + args.output + "' file.")
